use async_trait::async_trait;
use std::sync::Arc;

use sea_orm::{
    ColumnTrait, Condition, DatabaseConnection, DbErr, EntityTrait, PaginatorTrait, QueryFilter,
};

use crate::entities;

#[async_trait]
pub trait AccountGroupUserService: Send + Sync {
    /// Counts the number of account group users by account group id and user id.
    /// It also checks if the user is the account group creator.
    async fn count_by_account_group_and_user_and_is_account_group_creator(
        &self,
        account_group_id: &str,
        user_id: &str,
    ) -> Result<u64, DbErr>;
}

pub struct AccountGroupUserServiceImpl {
    db: Arc<DatabaseConnection>,
}

impl AccountGroupUserServiceImpl {
    pub fn new(db: Arc<DatabaseConnection>) -> Self {
        AccountGroupUserServiceImpl { db }
    }
}

#[async_trait]
impl AccountGroupUserService for AccountGroupUserServiceImpl {
    async fn count_by_account_group_and_user_and_is_account_group_creator(
        &self,
        account_group_id: &str,
        user_id: &str,
    ) -> Result<u64, DbErr> {
        let count = entities::prelude::AccountGroupUser::find()
            .filter(
                Condition::all()
                    .add(entities::account_group_user::Column::AccountGroupId.eq(account_group_id))
                    .add(entities::account_group_user::Column::UserId.eq(user_id))
                    .add(entities::account_group_user::Column::IsAccountGroupCreator.eq(true)),
            )
            .count(self.db.as_ref())
            .await?;

        Ok(count)
    }
}
